package com.deluxelx.soul.inn.service.task;

import cn.hutool.core.util.StrUtil;
import com.deluxelx.soul.inn.bean.search.History;
import com.deluxelx.soul.inn.common.util.RedisUtil;
import com.deluxelx.soul.inn.service.search.HistoryService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import java.util.List;

import static com.deluxelx.soul.inn.common.constant.HistoryConstant.historyTaskPattern;

/**
 * 搜索历史定时任务
 *      保证 redis 和 Mysql 数据一致性
 *
 * @author liaozihao
 * @date 2024-04-28 15:02
 */
@Component
@Slf4j
public class HistoryTask {

    @XxlJob(value = "MySearchHistoryHandler")
    public void mySearchHistoryHandler() {
        log.info("---------- 【咨询师】关注相关数据同步开始 ----------");
        mySearchHistoryTask();
        log.info("---------- 【咨询师】关注相关数据同步结束 ----------");
    }

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private HistoryService historyService;

    /**
     * 课程关注相关数据同步
     * 0 0 5 * * ?
     * 每天凌晨5点执行一次
     **/
    public void mySearchHistoryTask() {
        try {
            List<String> keys = redisUtil.scanKeys(historyTaskPattern);
            for (String key : keys) {
                String[] split = key.split(StrUtil.COLON);
                String userId = split[1];
                // todo 需要更改为获取 分数+value 形式
                List<History> historyList = redisUtil.rangeAllByScoreAsc(key, History.class);
                for (History history : historyList) {
                    Integer count = historyService.lambdaQuery()
                            .eq(History::getId, history.getId())
                            .eq(History::getUserId, userId)
                            .count();
                    if (count > 0) {
                        historyService.lambdaUpdate()
                                .set(History::getSearchTime, history.getSearchTime())
                                .set(History::getDeleteFlag, 0)
                                .eq(History::getId, history.getId())
                                .eq(History::getUserId, userId)
                                .update();
                    } else {
                        historyService.save(history);
                    }
                }
            }
        } catch (Exception e) {
            log.error("【搜索历史记录】相关数据同步异常", e);
        }
    }

}
